package com.ruoyi.common.utils;

import org.apache.poi.ss.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {

    /**
     * 读取Excel文件内容并转换为实体对象列表
     */
    public static <T> List<T> readExcel(InputStream inputStream, Class<T> clazz) throws IOException {
        List<T> dataList = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(inputStream);

        // 读取第一个工作表
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            return dataList;
        }

        // 获取表头行（第一行）
        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            return dataList;
        }

        // 遍历数据行
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row == null) continue;

            try {
                T entity = clazz.newInstance();
                Field[] fields = clazz.getDeclaredFields();

                // 遍历单元格并赋值给实体对象
                for (int cellNum = 0; cellNum < headerRow.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    if (cell == null) continue;

                    String cellValue = getCellValue(cell);
                    // 这里需要根据实际Excel列名与实体属性的映射关系进行赋值
                    // 简化实现：假设Excel列顺序与实体属性顺序一致
                    if (cellNum < fields.length) {
                        fields[cellNum].setAccessible(true);
                        fields[cellNum].set(entity, convertValue(fields[cellNum].getType(), cellValue));
                    }
                }
                dataList.add(entity);
            } catch (Exception e) {
                throw new RuntimeException("Excel数据转换失败，行号：" + rowNum, e);
            }
        }

        workbook.close();
        return dataList;
    }

    /**
     * 获取单元格值
     */
    private static String getCellValue(Cell cell) {
        if (cell == null) return "";

        String value = "";
        switch (cell.getCellType()) {
            case STRING:
                value = cell.getStringCellValue();
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    value = DateUtil.getJavaDate(cell.getNumericCellValue()).toString();
                } else {
                    value = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                value = cell.getCellFormula();
                break;
            default:
                value = "";
        }
        return value;
    }

    /**
     * 类型转换
     */
    private static Object convertValue(Class<?> type, String value) {
        if (value == null || value.isEmpty()) return null;

        if (type == String.class) {
            return value;
        } else if (type == Integer.class || type == int.class) {
            return Integer.parseInt(value);
        } else if (type == Long.class || type == long.class) {
            return Long.parseLong(value);
        } else if (type == Double.class || type == double.class) {
            return Double.parseDouble(value);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.parseBoolean(value);
        }
        return value;
    }
}
